<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Config;
use App\Models\SystemLog;
use App\Models\User\SystemUser;
use App\Service\UserService;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Intervention\Image\Facades\Image;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

/**
 * @group 用户api
 */
class UserController extends Controller
{
    //
    protected $service;
    public function __construct(UserService $service)
    {
        $this->service =  $service;
    }

    /**
     * 用户信息
     * @authenticated
     */
    public function info()
    {
        $user_id =  Auth::user()->id;
        $data = $this->service->info($user_id);
        return returnData($data);
    }

    /**
     * miniProgramLogin 小程序登录
     * @time:2020/2/4-17:35
     * @param Request $request
     * @author:dongdong
     * @authenticated
     * @bodyParam code required form The id of the location. Example:111111
     * @bodyParam parent_id 父级id Example:0
     * @bodyParam user_id form 使用测试code时，需登录的用户id Example:1334
     * @bodyParam pass form 使用测试code时 需要的通信密码： Example:dongdongidea
     * @response {
     * "data": {
     *          "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC8xMjcuMC4wLjE6ODAwMFwvZGluZ2dvYXBpXC91c2VyXC9taW5pcHJvZ3JhbVwvbG9naW4iLCJpYXQiOjE1ODA4MDg1OTMsImV4cCI6MTU4MTI0MDU5MywibmJmIjoxNTgwODA4NTkzLCJqdGkiOiJXV1dZb3daYVJJbWR6RlJIIiwic3ViIjoxMzM0LCJwcnYiOiJjNWFlZTViMDllOGE2Y2E1NTQyMDMyNmE0ZmJiNWYxNTA4ZTJlM2RlIn0.aqpXnuwv4fPbwMqYIZgNfyxGNs-xrmkfvOVL_fk2e08",
                "token_type": "bearer",
                "expires_in": 432000
     * },
     * "status_code": 2000,
     * "message" : "success"
     * }
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function miniProgramLogin(Request $request)
    {
        $code =  $request->get('code');
        $request->validate([
            'code' => 'required',
        ]);

        $user_id = $request->get('user_id');
        $pass = $request->get('pass');
        $parent_id = $request->get('parent_id', 0);

        $token = $this->service->miniProgramLogin($code, $parent_id, $user_id, $pass);

        return returnData([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60
        ],'miniProgramLogin success');
    }

    /**
     * login 账户登录
     * @time:2020/2/4-10:48
     * @param Request $request
     * @author:dongdong
     * @bodyParam username required The loginName of the location.
     * @bodyParam password required The password of the location.
     * @response {
     * "data": {
     * },
     * "status_code": 200,
     * "message" : "success"
     * }
     * @return \Illuminate\Http\JsonResponse
     */
    public function userLogin(Request $request)
    {
        $credentials = request(['phone', 'password']);

        if (! $token =   auth('api')->attempt($credentials)) {
            return returnData(['error' => 'Unauthorized 登录失败'],'Unauthorized 登录失败',5000);
        }
        $user =  auth('api')->user();
        $user->last_login = date("Y-m-d H:i:s");
        $user->save();
        SystemLog::create([
            'type' => 'login',
            'user_id' => $user->id,
            'message' => 'login success',
            'position' => 'UserController/userLogin',
            'info'  => $user->phone,
        ]);
        return returnData([
            'info' =>  auth('api')->user(),
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60
        ],'success');
    }

    /**
     * updateInfo 修改用户信息；
     * @time:2020/2/4-18:15
     *
     * @param Request $request
     * @author:dongdong
     * @bodyParam data required json对象或json字符串.
     * @response {
     * "data": {
     * },
     * "status_code": 200,
     * "message" : "success"
     * }
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function updateInfo(Request $request)
    {
        $request->validate([
            'data' => 'required'
        ]);
        $data = $request->get('data');

        if (is_string($data)) {
            $data = json_decode($data,true);
        }
        $user = auth()->user();
        $boolean = $this->service->updateInfo($data, $user);

        return returnData($boolean);

    }

    /**
     * getChild 获取 子集
     * @time:2020/1/30-12:46
     *
     * @author:dongdong
     * @queryParam example_id required The id of the location.
     * @bodyParam example_id required The id of the location.
     * @response {
     * "data": {
     * },
     * "status_code": 200,
     * "message" : "success"
     * }
     */
    public function getChild()
    {

    }

    /**
     * getNearByDistance 查询附件的人
     * @time:2020/2/6-9:26
     * @author:dongdong
     * @queryParam longitude required 经度 Example: 108
     * @queryParam latitude required 经度  Example: 30
     * @queryParam distance required 查询附件距离(米) Example: 500
     * @queryParam page   页数default 1 Example: 1
     * @queryParam limit  每页条数 default 15 Example: 15
     * @response {
     * "data": {
     * },
     * "status_code": 200,
     * "message" : "success"
     * }
     */
    public function getNearByDistance(Request $request)
    {
        $request->validate([
            'longitude' => 'required|numeric',
            'latitude' => 'required|numeric',
            'distance' => "numeric"
        ]);
        $longitude = $request->get('longitude');
        $latitude = $request->get('latitude');
        $distance =  $request->get('distance', 500);

        $nearData =  $this->service->getNearByDistance($longitude,$latitude,  $distance);

        return returnData($nearData);
    }

    /**
     * getQrcode 图片二维码[固定单图]
     * @time:2020/2/7-10:46
     * @author:dongdong
     * @response {
     * "data": {
     *  "share_url": "http://127.0.0.1:8000/make/1334/share.png【分享图片】",
        "qrcode_url": "http://127.0.0.1:8000/make/1334/qr1.png【纯二维码】"
     * },
     * "status_code": 200,
     * "message" : "success"
     * }
     */
    public function getQrcode()
    {
        $user = auth()->user();
        $user_id = $user->id;
        $qrcode = '';
        $path = public_path().'/make';
        $userPath = $path."/".$user_id;
        if(!is_dir($userPath)) {
            mkdir($userPath,0777,true);
        }
        $url = request()->getSchemeAndHttpHost().'/qrcode/'.$user_id;

        $qrpath = $path."/{$user_id}/qr1.png";

        QrCode::format('png')->size(355)->generate($url, $qrpath);
        $savepath = $path.'/'.$user_id.'/share.png';

        $static = public_path().'/static/qrcode.png';
        $phone = "1010100";
        $text = '全国统一热线:'.$phone;
        $fontPath = public_path().'/static/simkai.ttf';

        $image = Image::make(public_path().'/static/qrcode.png')
            ->insert($qrpath,'top-left',200,550)
            ->text($text, 180,1000, function ($font) use ($fontPath) {
                $font->file($fontPath);
                $font->size(30);
                $font->color("#d10909");
                $font->valign('center');
            })
            ->save($savepath);

        $img = request()->getSchemeAndHttpHost().'/make/'.$user_id.'/share.png';
        $qrcodeurl = request()->getSchemeAndHttpHost().'/make/'.$user_id.'/qr1.png';

        return returnData([
            'share_url' => $img,
            'qrcode_url' => $qrcodeurl,
        ]);
    }

    /**
     * getMultipleShareimg
     * @time:2020/3/6-13:23
     *  获取多个 用户分享推广图片
     * @author:dongdong
     * @queryParam example_id required The id of the location.
     * @bodyParam example_id required The id of the location.
     * @response {
        "status_code": 2000,
        "message": "success",
        "data": [
        "http://127.0.0.1:8000/make/user/101334/1_0_shareimg.png",
        "http://127.0.0.1:8000/make/user/101334/2_1_shareimg.png"
        ]
        }
     */
    public function getMultipleShareimg(Request $request)
    {
        $res = $this->service->getMultipleShareimg();
        return returnData($res);
    }

}
